package com.zlp.netty.buffer;

import lombok.extern.slf4j.Slf4j;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author: zhulaiping
 * @time: 2022/8/10 10:12
 */
@Slf4j
public class ByteBufferDemo {

    public static void main(String[] args) {

        try (FileChannel channel = new FileInputStream("data.txt").getChannel()){
            //IO流，缓冲区是数组，现在是buffer
            ByteBuffer buffer = ByteBuffer.allocate(10);
            int len;
            while ((len = channel.read(buffer))!=-1){
                buffer.flip(); //切换读模式
                while (buffer.hasRemaining()){
                    byte b = buffer.get();
                    log.debug("读取到的字符：{}",(char)b);
                }
                buffer.clear();//切换写模式
            }

            buffer.compact();//把未读的部分向前压缩，然后切换写模式
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
